<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="1200px" append-to-body custom-class="import-dialog">
      <div class="container">
        <div class="container-body" ref="containerBody">
          <el-form ref="form" :model="form" label-width="130px" :rules="rules" :disabled="isDetail">
            <div class="section">
              <div class="section-title">客户类型</div>
              <div class="section-content">
                <div class="client-type" v-if="!isDetail">
                  <div class="client-type-item"
                       :class="{active: form.clientType === item.value,disabled:data.cluePoolId}"
                       @click.stop="handleClientType(item.value)" v-for="item in clientTypeList"
                  >{{ item.label }}
                  </div>
                </div>
                <div v-if="isDetail">
                  <el-form-item label="客户类型：" prop="clientType" key="clientType">
                    {{clientTypeList.find(item=>item.value===form.clientType).label}}
                  </el-form-item>
                </div>
              </div>
            </div>
            <div class="section">
              <div class="section-title">基础信息</div>
              <div class="section-content">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="姓名：" prop="userName" key="userName">
                      <el-input v-model="form.userName" placeholder="请输入姓名" :disabled="data.cluePoolId&&isSalesman"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="电话：" prop="userPhone" key="userPhone">
                      <el-input v-model="form.userPhone" placeholder="请输入电话" maxlength="11" :disabled="data.cluePoolId&&isSalesman"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="性别：" prop="sex" key="sex">
                      <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%;">
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="2"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="微信/邮箱/其他" prop="openId" key="openId">
                      <el-input v-model="form.openId" placeholder="请输入微信/邮箱/其他"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
            <div class="section">
              <div class="section-title">需求信息</div>
              <div class="section-content">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="需求来源：" prop="cluePoolSource" key="cluePoolSource">
                      <el-select v-model="form.cluePoolSource" placeholder="请选择需求来源" style="width: 100%;">
                        <el-option :label="item.label" :value="item.value" v-for="item in dict.type.clue_pool_source"
                                   :key="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="紧急程度：" prop="urgencyDegree" key="urgencyDegree">
                      <el-select v-model="form.urgencyDegree" placeholder="请选择紧急程度" style="width: 100%;">
                        <el-option :label="item.label" :value="item.value" v-for="item in dict.type.urgency_degree"
                                   :key="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="期望租期：" prop="expectCheckInType" key="expectCheckInType">
                      <el-select v-model="form.expectCheckInType" placeholder="请选择" style="width: 100%;">
                        <el-option :label="item.label" :value="item.value"
                                   v-for="item in dict.type.clue_pool_expect_check_in_type"
                                   :key="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="可接受价格：" >
                      <el-row :gutter="10">
                        <el-col :span="8">
                          <el-input v-model="form.minimumPrice" placeholder="请输入" v-input.float="2"
                                    @blur="(e)=>form.minimumPrice=e.target.value===''?null:Number(e.target.value)"
                          ></el-input>
                        </el-col>
                        <el-col :span="8">
                          <el-input v-model="form.topPrice" placeholder="请输入" v-input.float="2"
                                    @blur="(e)=>form.topPrice=e.target.value===''?null:Number(e.target.value)"
                          ></el-input>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="需求户型：" prop="houseType" key="houseType">
                      <el-select v-model="form.houseType" placeholder="请选择需求户型" style="width: 100%;">
                        <el-option :label="item.label" :value="item.value" v-for="item in dict.type.house_type"
                                   :key="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>

                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="意向地址："  prop="premisesAddress" key="premisesAddress">
                      <el-input v-model="form.premisesAddress" placeholder="请输入意向地址" :disabled="data.cluePoolId&&isSalesman"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="备注：" prop="remark" key="remark">
                      <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" show-word-limit
                                maxlength="100" rows="4" v-if="!isDetail"
                      ></el-input>
                      <span v-else>{{form.remark? form.remark : '-'}}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>

          </el-form>
          <div class="section" v-if="isDetail">
            <div class="section-title">跟进记录</div>
            <div class="section-content">
              <div class="followUpRecord">
                <div class="followUpRecord__timeline">
                  <el-timeline :reverse="true">
                    <el-timeline-item
                      placement="bottom"
                      type="primary"
                      v-for="(item, index) in form.cluePoolRecordList"
                      :key="index"
                      :timestamp="item.createTime"
                    >
                      <div class="followUpRecord__timeline__item__content">
                        <span>{{ item.recordContent }}</span>
                      </div>
                    </el-timeline-item>
                  </el-timeline>
                  <!--     为空时，显示暂无记录       -->
                  <div v-if="!form.cluePoolRecordList || form.cluePoolRecordList.length === 0"
                       class="followUpRecord__timeline__empty"
                  >
                    暂无记录
                  </div>
                </div>
                <div class="followUpRecord__record">
                  <div class="followUpRecord__record__input">
                    <el-input
                      type="textarea"
                      placeholder="添加跟进记录，按enter 键提交"
                      v-model="recordForm.remark"
                      maxlength="200"
                      show-word-limit
                      @keyup.enter.native="handleAddRecord"
                    />
                  </div>
                  <div class="followUpRecord__record__button">
                    <el-button type="primary" size="mini" @click="handleAddRecord">发送</el-button>
                  </div>

                </div>

              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="close">取消</el-button>
        <el-button type="primary" size="small" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { debounce } from '@/utils'
import { addCluePool, addCluePoolRecord, getCluePool, updateCluePool } from '@/api/cluePool/cluePool'

export default {
  props: {
    title: {
      default: '录入'
    },
    show: {
      default: false
    },
    // 是否为销售员
    isSalesman: {
      default: false
    },
    userType: {
      default: '1' // 1.租客、2.业主
    },
    roleType: {
      default: '1' // 1.管理员、2.销售员
    },
    isDetail: {
      default: false // 是否为详情页
    }, // 是否为详情页
    data: {
      default: () => {
        return {}
      }
    }
  },
  dicts: ['push_channel', 'clue_pool_state', 'house_type', 'house_number_type','clue_pool_source','urgency_degree','clue_pool_expect_check_in_type'],
  data() {
    return {
      recordForm: {
        cluePoolId: '',
        remark: ''
      },
      form: {
        userType: '1'
      },
      rules: {
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        userPhone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    },
    clientTypeList: {
      get() {
        if (this.userType === '1') {
          return [
            { label: '公共客户(公司内都可查看)', value: '1' },
            { label: '私人客户(只有自己可查看)', value: '2' }
          ]
        } else if (this.userType === '2') {
          return [
            { label: '公盘(公司内都可查看)', value: '1' },
            { label: '私盘(只有自己可查看)', value: '2' }
          ]
        }
      },
      set(val) {
      }
    }
  },
  watch: {
    show: {
      handler(newVal) {
        if (newVal) {
          this.init()
        }
      }
    }
  },
  methods: {
    init() {
      this.reset()
      if (this.data.cluePoolId) {
        this.getInfo()
      }
      console.log("form", this.form)
    },
    reset() {
      this.form = {
        'clientType': '1', //客户类型：1.公客、2.私客
        'userType': '1', //用户类型：1.租客、2.业主
        'userName': '', //用户姓名
        'userPhone': '', //用户手机号
        'sex': '', //性别：1.男、2.女
        'openId': '', //微信/邮箱/其他
        'cluePoolSource': '', //需求来源：1.到访、2.网络、3.委托（字典：clue_pool_source）
        'urgencyDegree': '', //紧急程度：1.立即入住、2.一周内、3.一个月内、4.先看看（字典：urgency_degree）
        'expectCheckInType': '', //期望租期：1.一个月、2.三个月、3.半年、4.一年、5.更久（字典：clue_pool_expect_check_in_type）
        'premisesAddress': '', //小区地址
        'minimumPrice': null, //最低价
        'topPrice': null, //最高价
        'houseType': '', //户型：1.单间、2.一居、3.两居、4.三居、5.四居、6.其他（字典：house_type）
        'houseArea': null, //房屋面积
        'decorateSituationType': '', //装修情况类型：1.豪装、2.粗装、3.简装、4.毛坯（字典：decorate_situation_type）
        'rentHolidayState': '', //免租期(0.否,1.是)
        'remark': '' //备注
      }
      this.resetForm('queryForm')
    },
    // 获取详情
    getInfo() {
      if (!this.data.cluePoolId) return
      getCluePool(this.data.cluePoolId).then(response => {
        this.form = response.data
      })
    },
    // 添加跟进记录
    handleAddRecord() {
      let form = {
        cluePoolId: this.form.cluePoolId,
        remark: this.recordForm.remark
      }
      addCluePoolRecord(form).then(res => {
        this.$message.success(res.msg || '提交成功')
        this.getInfo()
        this.recordForm.remark = ''
      })

    },
    handleClientType(val) {
      if(this.data.cluePoolId) return
      this.form.clientType = val
    },
    /** 确定 */
    handleSubmit: debounce(function() {
      console.log('handleSubmit', this.form)
      this.$refs.form.validate((valid) => {
        if (valid) {
          let api = ''
          if (this.data.cluePoolId) {
            api = updateCluePool
          }else{
            api = addCluePool
          }
          api(this.form).then(res => {
            this.$message.success(res.msg || '提交成功')
            this.$emit('success')
            this.close()
          })

        } else {
          console.log('error submit!!')
          return false
        }
      })
    }, 500, true),
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/dialog.scss";

.container {
  overflow: hidden;
  height: 100%;
  position: relative;

  .container-body {
    overflow-y: auto;
    height: 90%;

    .section {
      padding: 10px;

      .section-title {
        padding: 8px;
        border-radius: 4px;
        margin-bottom: 20px;
        font-size: 15px;
        font-weight: bold;
      }

      .section-content {
        .client-type {
          display: flex;
          justify-content: center;

          .client-type-item {
            padding: 5px;
            border: 1px solid #797979;
            cursor: pointer;
            font-size: 12px;
            width: 200px;
            text-align: center;

            &.active {
              color: #2CB5F2;
              border-color: #2CB5F2;
              cursor: default;
            }
            &.disabled {
              background: #F2F2F2;
              cursor: default;
            }
          }
        }

        .followUpRecord {
          margin: 20px 0;

          .followUpRecord__img{
            display: grid;
            grid-template-columns:repeat(auto-fit, 100px);
            grid-gap: 10px;
            width: 100%;
          }

          .followUpRecord__timeline {
            height: 300px;
            overflow: auto;
            margin: 30px 0;
            border: 1px solid #797979;
            padding: 10px;

            .followUpRecord__timeline__item__content {
              display: flex;
              align-items: center;
            }
          }

          .followUpRecord__table {
            .followUpRecord__table__fee {
              display: flex;
              justify-content: space-between;
              margin-top: 20px;
            }

            .followUpRecord__table__payment {
              display: flex;
              justify-content: space-between;
              font-size: 16px;
              margin-bottom: 20px;
              color: #2E9038;
              width: 50%;
            }

            .followUpRecord__table__total {
              text-align: right;

              .followUpRecord__table__total__cost {
                color: #F6A030;
              }

              .followUpRecord__table__total__createTime {
                color: #8E8E8E;
                font-size: 14px;
              }
            }
          }

          .followUpRecord__rate-container {
            display: flex;
            margin-top: 20px;
            font-size: 16px;

            .followUpRecord__rate-container__rate {
              width: 500px;
              margin-right: 20px;

              .followUpRecord__rate-container__rate__item {
                display: flex;
                align-items: baseline;
                margin-bottom: 10px;

                &:last-child {
                  margin-bottom: 0;
                }

              }

              ::v-deep.el-rate {
                heigth: auto;
              }

              ::v-deep.el-rate__icon {
                font-size: 30px;
              }
            }

            .followUpRecord__rate-container__info {

              .followUpRecord__rate-container__info__item {
                display: flex;
                margin-bottom: 10px;
                align-items: baseline;

                &:last-child {
                  margin-bottom: 0;
                }

                .followUpRecord__rate-container__info__item-label {
                  margin-right: 10px;
                  font-weight: bold;
                }

                .followUpRecord__rate-container__info__item-value {
                  color: #F6A030;
                }

                .followUpRecord__rate-container__info__item__image {
                  display: flex;
                  flew-wrap: wrap;

                  .followUpRecord__rate-container__info__item__image__item {
                    margin-right: 10px;

                    &:last-child {
                      margin-right: 0;
                    }
                  }
                }
              }
            }
          }

          .followUpRecord__record {
            display: flex;
            align-items: flex-end;

            .followUpRecord__record__input {
              flex: 1;
            }

            .followUpRecord__record__button {
              margin-left: 10px;
            }
          }
        }
      }
    }
  }
}
</style>
